//
//  MyViewController.m
//  AAIM
//
//  Created by awh on 2019/11/24.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "MyViewController.h"
#import "CenterHeaderView.h"
#import "CenterTableViewCell.h"
#import "UserInfoViewController.h"
#import "SetViewController.h"
#import "InviteViewController.h"
#import "CodeSeeViewController.h"
#define ORIGINAL_MAX_WIDTH 640.0f

@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UserInfoViewDelegate>
@property (nonatomic,strong) UITableView * userCenterTableView;
@property (nonatomic,strong) CenterHeaderView * headerView;
@property (nonatomic,copy) NSArray * titleAry;
@property (nonatomic,copy) NSString * appVersion;
@property (nonatomic,strong)NSDictionary * dataDic;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.userCenterTableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _appVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"appVersion"];
    self.view.backgroundColor = [UIColor whiteColor];
    self.gk_navigationBar.hidden = YES;
    _titleAry = @[@[@{@"imageStr":@"icon-邀请有礼",@"titleStr":@"邀请好友"}],@[@{@"imageStr":@"icon-口令看看",@"titleStr":@"口令看看"}],@[@{@"imageStr":@"icon-设置",@"titleStr":@"设置"}],@[@{@"imageStr":@"icon-当前版本",@"titleStr":@"当前版本"}]];
    //获取数据
    [self getUserData];
        
}

- (void)getUserData{
  UserModel * model = [LoginManager shareLoginManager].userModel;
    [RequestData GetUserCenterDataWithToken:model.token userUUid:model.uuid Success:^(NSDictionary * _Nonnull Dict) {
//        NSLog(@"成功啦：%@",Dict);
        KWeakSelf;
        weakSelf.dataDic = Dict;
        weakSelf.headerView.dataDic = weakSelf.dataDic;
        model.fuuid = Dict[@"data"][@"fuuid"];
        model.head = [NSString stringWithFormat:@"%@%@",userHeaderImage,Dict[@"data"][@"head"]];
        [[LoginManager shareLoginManager] saveLoginCustomer:model];
        [weakSelf.userCenterTableView reloadData];
    } failure:^(NSString * _Nonnull errMsg) {
        NSLog(@"请求出错了：%@",errMsg);

        if ([errMsg isEqualToString:@"未登录"]) {
            [self showTipHudWithText:@"请重新登录"];
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [[LoginManager shareLoginManager] saveLoginCustomer:[[UserModel alloc]init]];
            [[LoginManager shareLoginManager]loginOut];
        });
        }else{
           [self showTipHudWithText:errMsg];
        }
           
        
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.gk_navLineHidden = YES;
    self.gk_statusBarHidden = YES;

}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

   
}
//修改头像
- (void)changeHeaderImage{
    UIAlertController * alerController = [UIAlertController alertControllerWithTitle:@"" message:@"上传头像图片" preferredStyle:UIAlertControllerStyleActionSheet];
      
      UIAlertAction * cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
          
      }];
      
      UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
          [self openCamera];
      }];
     
      UIAlertAction * photo = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
          [self openPhotoLibrary];
      }];
      
      [alerController addAction:camera];
      [alerController addAction:photo];
      [alerController addAction:cancle];
      
      [self presentViewController:alerController animated:YES completion:nil];
     
}


/*** 调用照相机 */
- (void)openCamera{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES; //可编辑
    //判断是否可以打开照相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"没有摄像头");
        [self showTipHudWithText:@"打开相机失败"];
    }
}
/*** 打开相册  */
-(void)openPhotoLibrary{
    // 进入相册
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:^{
            NSLog(@"打开相册");
        }];
    }else{
        NSLog(@"不能打开相册");
          [self showTipHudWithText:@"打开相册失败"];
    }
}

#pragma mark - UIImagePickerControllerDelegate
// 拍照完成回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info{
//    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
//    NSLog(@"finish..");
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        //图片存入相册
//        _headerView.headImageView.image = image;
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    if(picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){
        
    }
    UIImage *scaleImage = [self imageByScalingToMaxSize:image];
    [self upLoadHeaderImage:scaleImage withToken:[LoginManager shareLoginManager].userModel.token];

    [self dismissViewControllerAnimated:YES completion:nil];
}

//上传头像
- (void)upLoadHeaderImage:(UIImage *)image withToken:(NSString *)token{
    [LoginRequestLogic upLoadFile:image withToken:token Success:^(NSDictionary * _Nonnull Dict) {
        NSLog(@"134567890-----%@",Dict);
        KWeakSelf;
        if ([Dict[@"code"] integerValue] == 200) {
            UserModel * model = [LoginManager shareLoginManager].userModel;
            model.head = [NSString stringWithFormat:@"%@%@",userHeaderImage,Dict[@"data"]];
            [[LoginManager shareLoginManager] saveLoginCustomer:model];
            [weakSelf changeUserInfo:Dict[@"data"] withImage:image];
        }
    } failure:^(NSString * _Nonnull errMsg) {
        NSLog(@"出错了：%@",errMsg);
         [self showTipHudWithText:@"修改失败"];
    }];
}

- (void)changeUserInfo:(NSString *)head withImage:(UIImage *)image{

    KWeakSelf;
    [RequestData changeUserInfoWithToken:[LoginManager shareLoginManager].userModel.token userUUid:[LoginManager shareLoginManager].userModel.uuid areaStr:@"" withBirthday:@"" withCity:@"" withCompany:@"" withHead:head withIsVerify:@"" withJob:@"" withNickName:@"" withProvince:@"" withRemark:@"" withSex:@"" Success:^(NSDictionary * _Nonnull Dict) {
            weakSelf.headerView.headImageView.image = image;
        [weakSelf showTipHudWithText:@"修改成功"];

    } failure:^(NSString * _Nonnull errMsg) {

        [weakSelf showTipHudWithText:@"修改失败"];
    }];
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
 
    return _titleAry.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_titleAry[section] count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    CenterTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"centerCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"CenterTableViewCell" owner:self options:nil]firstObject];
//        cell = [[CenterTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"centerCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = _titleAry[indexPath.section][indexPath.row];
    if (indexPath.section ==2) {
        cell.otherLabel.hidden = YES;
        if (indexPath.row == 3) {
            cell.line.hidden = YES;
        }
    }else{
     cell.line.hidden = YES;
        if (indexPath.section == 0) {
            cell.otherLabel.text = @"暂无邀请码";
        }else if (indexPath.section == 1){
            cell.otherLabel.hidden = YES;
        }else{
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            cell.otherLabel.text = app_Version;
        }
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    if (indexPath.section == 0) {
        InviteViewController * inviteVC = [[InviteViewController alloc]init];
        inviteVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:inviteVC animated:YES];
    }else if (indexPath.section == 2){
        SetViewController * setVC = [[SetViewController alloc]init];
        setVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:setVC animated:YES];
    }else if(indexPath.section == 1){
        CodeSeeViewController * codeSeeVC = [[CodeSeeViewController alloc]init];
        codeSeeVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:codeSeeVC animated:YES];
    }else{
         NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

        NSString * appV = [[NSUserDefaults standardUserDefaults]objectForKey:@"appVersion"];
        if ([appV isEqualToString:app_Version]) {
            [self showTipHudWithText:@"已是最新版本"];
        }else{
            [self showTipHudWithText:@"请下载最新版本"];
        }
      
    }
    
}

//区头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView * sectionView = [UIView new];
    sectionView.backgroundColor = [UIColor colorWithHex:@"f4f4f4"];

        return sectionView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * sectionView = [UIView new];
    sectionView.backgroundColor = [UIColor colorWithHex:@"f4f4f4"];
    
    return sectionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.f;
}


//区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  
    return 9.0f;

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

//点击前往用户信息
- (void)goUserInfoPage{
    UserInfoViewController * userInfoVC = [[UserInfoViewController alloc]init];
    userInfoVC.delegate = self;
    userInfoVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:userInfoVC animated:YES];
}

//代理修改昵称展示
- (void)changeUserInfoDisPlay{
    [self getUserData];
}

- (UITableView *)userCenterTableView{
    if (!_userCenterTableView) {
        if (IS_iPhoneX) {
          _userCenterTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,-kStatusBarHeight, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
        }else{
          _userCenterTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,-kStatusBarHeight, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
        }
        
        _userCenterTableView.tableFooterView = [UIView new];
        _userCenterTableView.delegate = self;
        _userCenterTableView.dataSource = self;
        _userCenterTableView.backgroundColor = KHEXCOLOR(@"#F4F4F4");
        _userCenterTableView.separatorStyle = UITableViewCellSelectionStyleNone;//点击cell不变色
        _headerView = [[CenterHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 181)];

//        _headerView.headImageView.image = [UIImage imageNamed:@"我的-头像"];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goUserInfoPage)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        [_headerView.moreImageView addGestureRecognizer:tap];
        UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goUserInfoPage)];
        tap2.numberOfTapsRequired = 1;
        tap2.numberOfTouchesRequired = 1;
        [_headerView addGestureRecognizer:tap2];
       
        UITapGestureRecognizer * tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeHeaderImage)];
        tap3.numberOfTapsRequired = 1;
        tap3.numberOfTouchesRequired = 1;
        [_headerView.headImageView addGestureRecognizer:tap3];
        
//        _headerView.nameLabel.text = @"钢铁女孩";
//        _headerView.accountLabel.text = @"账号：1425733787@qq.com";
        if (_dataDic) {
            _headerView.dataDic = _dataDic;
        }
        _userCenterTableView.tableHeaderView = _headerView;
        
//        [_userCenterTableView registerClass:[CenterHeaderView class] forHeaderFooterViewReuseIdentifier:@"headerView"];
    }
    return _userCenterTableView;
}
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    //if(newImage == nil) BTIMLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
